#!/usr/bin/env bash

source ./config/env.sh
clear

mkdir -p ${K8S_DATA}/config/dashboard/yaml

mkdir -p ${K8S_CA_DIR}/dashboard


cp ${K8S_DATA}/unpack/kubernetes/cluster/addons/dashboard/* ${K8S_DATA}/config/dashboard/yaml


cat > ${K8S_DATA}/config/dashboard/yaml/dashboard-service.yaml << EOF
apiVersion: v1
kind: Service
metadata:
  name: kubernetes-dashboard
  namespace: kube-system
  labels:
    k8s-app: kubernetes-dashboard
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: Reconcile
spec:
  type: NodePort
  selector:
    k8s-app: kubernetes-dashboard
  ports:
  - port: 443
    targetPort: 8443
EOF

#\cp ${K8S_DATA}/config/dashboard/yaml/dashboard-service.yaml ${K8S_DATA}/unpack/kubernetes/cluster/addons/dashboard/dashboard-service.yaml
#cp ${K8S_DATA}/unpack/kubernetes/cluster/addons/dashboard/* ${K8S_DATA}/config/dashboard/yaml

cd ${K8S_DATA}/config/dashboard/yaml

sed -i "s#image: k8s.gcr.io/kubernetes-dashboard-amd64:v1.10.1#image: mirrorgooglecontainers/kubernetes-dashboard-amd64:v1.10.1#g" ${K8S_DATA}/config/dashboard/yaml/dashboard-controller.yaml

${K8S_BIN_DIR}/kubectl create -f  .

sleep 20

${K8S_BIN_DIR}/kubectl get deployment kubernetes-dashboard  -n kube-system
${K8S_BIN_DIR}/kubectl --namespace kube-system get pods -o wide
${K8S_BIN_DIR}/kubectl get services kubernetes-dashboard -n kube-system

cd ${K8S_CA_DIR}/dashboard

${K8S_BIN_DIR}/kubectl create sa dashboard-admin -n kube-system
${K8S_BIN_DIR}/kubectl create clusterrolebinding dashboard-admin --clusterrole=cluster-admin --serviceaccount=kube-system:dashboard-admin
ADMIN_SECRET=$(${K8S_BIN_DIR}/kubectl get secrets -n kube-system | grep dashboard-admin | awk '{print $1}')
DASHBOARD_LOGIN_TOKEN=$(${K8S_BIN_DIR}/kubectl describe secret -n kube-system ${ADMIN_SECRET} | grep -E '^token' | awk '{print $2}')


${K8S_BIN_DIR}/kubectl config set-cluster kubernetes \
  --certificate-authority=${K8S_CA_DIR}/admin/ca.pem \
  --embed-certs=true \
  --server=${APISERVER} \
  --kubeconfig=dashboard.kubeconfig

# 设置客户端认证参数，使用上面创建的 Token
${K8S_BIN_DIR}/kubectl config set-credentials dashboard_user \
  --token=${DASHBOARD_LOGIN_TOKEN} \
  --kubeconfig=dashboard.kubeconfig

# 设置上下文参数
${K8S_BIN_DIR}/kubectl config set-context default \
  --cluster=kubernetes \
  --user=dashboard_user \
  --kubeconfig=dashboard.kubeconfig

# 设置默认上下文
${K8S_BIN_DIR}/kubectl config use-context default --kubeconfig=dashboard.kubeconfig